# -*- coding: utf-8 -*-

from datetime import *
import time
import Cookie
import random

from google.appengine.ext import db  
from google.appengine.api import users

from django.http import HttpResponse
from django.utils.html import escape
from django.shortcuts import render_to_response
from appengine_utilities.sessions import Session
from appengine_utilities.flash import Flash

from templates import templatesfile
from settings import *
from ccutils import *
from xmsmodels import *
from zipme import *
from language import _T_

def __checkGroupAuth__(curUser,group,auth='user'):
    if auth == 'user':
        return curUser and group and curUser.IsUserOfGroup(group)
    if auth == 'admin':
        return curUser and group and curUser.IsAdminOfGroup(group)
    if auth == 'owner':
        return curUser and group and curUser.IsOwnerOfGroup(group)

@requires_login 
def index(request):
    flash = Flash()
    googleuser = users.get_current_user()
    curUser = XMSUser.GetXMSUserByUser(googleuser)
    context = {'user':googleuser,
           'xmsuser': curUser,
           'flash':flash,}
    
    session = Session()
    lang = session.get('lang', 'en-us')
    if request.GET:
        lang=(request.GET['lang'])
        if curUser:
            curUser.Language = lang
            curUser.put()             
    
    if curUser and curUser.Actived:
        lang = curUser.Language
        session['CurrentUser'] = curUser
        context.update({ 'groups':curUser.GetAllGroups()[:GROUPS_SHOW_IN_WELCOME],})
    else:
        #session.delete()
        pass
    session['lang'] = lang
    return render_to_response(templatesfile[lang]['index'], context)

@check_current_user                        
def summary(request, groupname=None):
    session = Session()

    if request.POST:
        groupname = request.POST.get('groupselect',None).strip()
    if groupname:
        curGroup = XMSGroup.GetActivedGroupByName(unicode(escape(groupname),'utf-8'))
        if not curGroup:
            return HttpResponseRedirect('/')
        session['CurrentGroup'] = curGroup.GroupName
        return HttpResponseRedirect('/summary')           
    
    flash = Flash()   
    curGroup = XMSGroup.GetActivedGroupByName(session.get('CurrentGroup',None)) 
    curUser = session.get('CurrentUser', None)      
    if not __checkGroupAuth__(curUser,curGroup,'user'):
        return HttpResponseRedirect("/")
      
    this_month = notpayCount = total_notpay = \
    total_income = total_paied = 0
    today = datetime.now()
    for payout in curGroup.GetAllPayouts():
        if payout.Datetime.year == today.year and \
            payout.Datetime.month == today.month:
            this_month += payout.Money
        if payout.IsPay == True:
            total_paied += payout.Money
        else:
            notpayCount += 1
            total_notpay += payout.Money
    total_payout = total_notpay + total_paied
    
    for income in curGroup.GetAllIncomes():
        total_income += income.Money
    
    summary = {'expend_this_month': this_month, 
               'notpayCount':notpayCount, 
               'total_notpay':total_notpay,
               'total_income':total_income, 
               'payedout':total_payout - total_notpay, 
               'remaining': total_income - total_payout + total_notpay, 
               'balance':total_income -  total_payout,
               } 
    return render_to_response(templatesfile[curUser.Language]['summary'],{'curUser': curUser, 'curGroup':curGroup,
                                              'show_summary': True,
                                              'summary': summary,
                                              'isAdmin':curUser.IsAdminOfGroup(curGroup),
                                              'flash':flash,})

#@check_current_user_and_group
def notpay(request):
    session = Session()
    curGroup = XMSGroup.GetActivedGroupByName(session.get('CurrentGroup',None))          
    curUser = session.get('CurrentUser', None)
    if not __checkGroupAuth__(curUser,curGroup,'user'):
        return HttpResponseRedirect("/")
    
    flash = Flash()
    if request.POST:
        if curUser.IsAdminOfGroup(curGroup):
            li = []
            for key in request.POST.getlist('ispay'):
                li.append(key)
            count = 0
            for payout in XMSPayout.get(li):
                payout.Approver = curUser
                payout.IsPay = True
                if payout.save():
                    count += 1
            flash.msg = _T_('items_paid',curUser.Language) % (count) 
            return HttpResponseRedirect("/notpay")
        else:
            return HttpResponseRedirect("/logout")
    try:
        page_index=int (request.GET['page'])
    except:
        page_index=1
            
    notpaylist = curGroup.Payouts.filter('IsPay =', False).order("Datetime")
    entries,links=Pager(query=notpaylist,items_per_page=PAGER_ITEMS_PER_PAGE ,pages_follow = PAGER_PAGES_FOLLOW ).fetch(page_index)
         
    notpay = {'count': links['count'], 'list':entries}
    isAdmin = True
    if not curUser.IsAdminOfGroup(curGroup):
        flash.msg = _T_('no_auth',curUser.Language)
        isAdmin = False
    return render_to_response(templatesfile[curUser.Language]['notpay'],{'curUser': curUser,'curGroup':curGroup,
                                             'show_notpay': True,
                                             'notpay': notpay,
                                             'pager':links,
                                             'flash':flash,
                                             'isAdmin':isAdmin,})

#@check_current_user_and_group  
def additem(request):
    session = Session()
    curGroup = XMSGroup.GetActivedGroupByName(session.get('CurrentGroup',None))          
    curUser = session.get('CurrentUser', None)
    if not __checkGroupAuth__(curUser,curGroup,'user'):
        return HttpResponseRedirect("/")
    
    additem = {'showpayout': 1, 'showincome':0 , 'isAdmin': curUser.IsAdminOfGroup(curGroup),}
    flash = Flash()
    if request.POST:
        if request.POST.has_key("show") :
            showIncome = (str(request.POST["show"]).strip() == "Income")
            additem.update({'showpayout': not showIncome, 'showincome':showIncome } )
        else:
            showIncome = (str(request.POST["post"]).strip() == "post_income")
            additem.update({'showpayout': not showIncome, 'showincome':showIncome } )
            
            description = unicode(escape(request.POST["description"]).strip(), 'utf-8')
            if len(description) <= 0:
                flash.msg = _T_('need_desc',curUser.Language)      
            else:
                if str(request.POST["post"]).strip() == "post_income":
                    if not additem['isAdmin']:
                        flash.msg = _T_('no_auth',curUser.Language)
                        return HttpResponseRedirect("/logout")
                    income = XMSIncome(Group = curGroup, Submiter = curUser) 
                    d = time.strptime(request.POST["date"],"%Y-%m-%d")
                    income.Datetime = datetime( d[0],d[1],d[2] )
                    income.Money = float(request.POST["money"])
                    income.User = XMSUser.GetXMSUserByNickName(unicode(escape(request.POST["username"].strip()),'utf-8'))
                    income.Details = description
                    if income.put():
                        flash.msg = _T_('income_added',curUser.Language) % \
                         {'money':income.Money,'user':income.User.NickName}
                    
                    
                else:
                    payout = XMSPayout(Group = curGroup) 
                    d = time.strptime(request.POST["date"],"%Y-%m-%d")
                    payout.Datetime = datetime( d[0],d[1],d[2] )
                    payout.Money = float(request.POST["money"])
                    payout.User = XMSUser.GetXMSUserByNickName(unicode(escape(request.POST["username"]).strip(),'utf-8'))
                    payout.Details = description
                    payout.IsPay = request.POST.has_key("haspay") and bool(request.POST["haspay"] == "on")
                    if payout.IsPay:
                        payout.Approver = payout.User
                    if payout.put():
                        flash.msg = _T_('payout_added',curUser.Language) % {'money':payout.Money,'user':payout.User.NickName}
    else:
        pass
    

    userlist = [curUser.NickName]
    if additem['isAdmin']:
        userlist = [u.NickName for u in curGroup.GetAllUsers()]
    elif additem['showincome'] == 1:
        additem.update({'showpayout': 1, 'showincome':0 } )
        flash.msg = _T_('no_auth',curUser.Language)
    
    css = (r'/static/styles/calendar-blue2.css',)
    response = render_to_response(templatesfile[curUser.Language]['additem'], {'curUser': curUser,'curGroup':curGroup,
                                              'show_additem': True,
                                             'additem': additem,
                                             'selectuser':curUser.NickName, 
                                             'userlist': userlist,
                                             'flash':flash,
                                             'css':css,
                                             'isAdmin': additem['isAdmin'],})
    return response


#@check_current_user_and_group
def incomes(request):
    session = Session()   
    curUser = session.get('CurrentUser', None)
    curGroup = XMSGroup.GetActivedGroupByName(session.get('CurrentGroup',None))          
    if not __checkGroupAuth__(curUser,curGroup,'user'):
        return HttpResponseRedirect("/")
    
    try:
        page_index=int (request.GET['page'])
    except:
        page_index=1
           
    incomelist = curGroup.GetIncomesByDate()
    entries,links=Pager(query=incomelist,items_per_page=PAGER_ITEMS_PER_PAGE,pages_follow = PAGER_PAGES_FOLLOW ).fetch(page_index)
         
    details = {'count': links['count'], 'entries':entries}
    flash = Flash()
    return render_to_response(templatesfile[curUser.Language]['details'], {'curUser': curUser, 
                                               'show_incomes': True,
                                               'curGroup':curGroup,
                                               'details': details,
                                               'pager':links,
                                               'flash':flash,
                                               'isAdmin': curUser.IsAdminOfGroup(curGroup),})

#@check_current_user_and_group
def payouts(request):
    session = Session()   
    curUser = session.get('CurrentUser', None)
    curGroup = XMSGroup.GetActivedGroupByName(session.get('CurrentGroup',None))    
    if not __checkGroupAuth__(curUser,curGroup,'user'):
        return HttpResponseRedirect("/")      

    try:
        page_index=int (request.GET['page'])
    except:
        page_index=1
           
    payoutlist = curGroup.GetPayoutsByDate()
    entries,links=Pager(query=payoutlist,items_per_page=PAGER_ITEMS_PER_PAGE,pages_follow = PAGER_PAGES_FOLLOW ).fetch(page_index)
         
    details = {'count': links['count'], 'entries':entries}
    flash = Flash()
    return render_to_response(templatesfile[curUser.Language]['details'], {'curUser': curUser, 
                                               'show_payouts': True,
                                               'curGroup':curGroup,
                                               'details': details,
                                               'pager':links,
                                               'flash':flash,
                                               'isAdmin': curUser.IsAdminOfGroup(curGroup),})

#@check_current_user_and_group
def report(request):
    session = Session()  
    curUser = session.get('CurrentUser', None)
    curGroup = XMSGroup.GetActivedGroupByName(session.get('CurrentGroup',None))
    if not __checkGroupAuth__(curUser,curGroup,'user'):
        return HttpResponseRedirect("/")
    
    charttype = 'bar'
    reporttype = 'date'
    count = 6
    if request.POST:
        charttype = request.POST.get('charttype','bar')
        reporttype = request.POST.get('reporttype','date')
        count = int(request.POST.get('count',6))
        pass
    
    size = (600,450)
    if charttype == "pie":
        size = (650,400)
    imagepath = "/genreport/%s/%s/%d/%d/%d/" \
                %(charttype,reporttype,count,size[0],size[1])
#    imagepath = XMSReport.GetReportPath(charttype,\
#                                         reporttype, count, \
#                                         title="报表", size=size)
    flash = Flash()
    selectedreport = {'charttype':charttype,'reporttype':reporttype,'count':count}
    return render_to_response(templatesfile[curUser.Language]['report'], {'curUser': curUser,
                                'show_report': True,'curGroup':curGroup,
                                'flash':flash,'size':size,
                                'imagepath':imagepath,
                                'selectedreport':selectedreport,
                                'isAdmin': curUser.IsAdminOfGroup(curGroup),})
    
    
